import { defineStore } from 'pinia'
import { getUserInfo, getRouters, logout } from '@/api/core'

export const useUserStore = defineStore('user', {
  state: () => {
    // 初始化时从 localStorage 获取 token
    const token = localStorage.getItem('token') || null

    return {
      token,
      userInfo: {},
      roles: [], // 角色
      permissions: [], // 按钮权限
      routers: [], // 动态路由
      noHasDynamicRouters: false, // 没有动态路由
    }
  },

  getters: {
    // 是否已登录
    isLoggedIn: (state) => {
      return state.token !== null && state.token !== ''
    },

    // 是否有某个权限
    hasPermission: (state) => (permission) => {
      // 如果有 * 权限，表示所有权限
      if (state.permissions.includes('*')) {
        return true
      }
      return state.permissions.includes(permission)
    },

    // 是否有某个角色
    hasRole: (state) => (role) => {
      return state.roles.includes(role)
    }
  },

  actions: {
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },

    setUserInfo(userInfo) {
      this.userInfo = userInfo
    },

    setRoles(roles) {
      this.roles = roles
    },

    setPermissions(perms) {
      this.permissions = perms
    },

    setRouters(routers) {
      this.routers = routers
    },

    // 获取用户信息
    fetchUserInfo() {
      // 直接返回 Promise，不包裹 try/catch（让错误向上传递）
      return getUserInfo()
        .then((response) => {
          this.setUserInfo(response.userInfo); // 接口成功时正常处理
          this.setRoles(response.roles || []);
          this.setPermissions(response.permissions || []);
          return response;
        })
        .catch((error) => {
          console.log('获取用户信息出错', error);
          throw error; // 关键：抛出错误，让路由守卫捕获
        });
    },

    // 获取路由信息
    fetchRouters() {
      return getRouters()
        .then((routers) => {
          if (routers.length === 0) {
            this.noHasDynamicRouters = true;
          }
          this.setRouters(routers);
          return routers;
        })
        .catch((error) => {
          console.log('获取路由信息出错', error);
          throw error; // 抛出错误
        });
    },

    // 登出
    async logout() {
      try {
        await logout()
      } catch (error) {
        console.error('登出失败:', error)
      } finally {
        console.log('登出成功')
        this.clearUserData()
      }
    },

    // 清除用户数据
    clearUserData() {
      this.token = null
      this.userInfo = {}
      this.roles = []
      this.permissions = []
      this.routers = []
      this.noHasDynamicRouters = false
      localStorage.removeItem('token')
    }
  }
}) 